/*
 * main.cpp
 *
 *  Created on: 2011-04-17
 *      Author: jacek
 */
#include <Event.h>
#include <Object.h>
#include <Component.h>
#include "NetUDPReceiver.h"
#include <iostream>
#include <Socket.h>
#include <vector>

using namespace std;
using namespace Net;

class ServerOut: public Component {
public:
	vector<NetAddress> objects;
	Socket gameSock;
	Package package;
	ServerOut() {
		gameSock.CreateSendingSocket(Socket::UDP);
		objects.push_back(NetAddress("127.0.0.1", 50003));

	}
	~ServerOut() {
	}
	virtual void Updata(Event event) {

	}
	virtual void Intialization() {

	}
	virtual void Dispose() {

	}
	virtual void SendEvent(Event event) {

		cout << "Receive package " << sizeof(event) << " bytes, destination="
				<< event.destination << " sender=" << event.sender << " type="
				<< event.type << endl;

		Event pom;
		pom.type = NET_ANSWERE;
		pom.destination=12;
		pom.sender=0;
		cout << "Send package " << sizeof(pom) << " bytes, destination="
								<< pom.destination << " sender=" << pom.sender << " type="
								<< pom.type << endl;
		ConvertEventHostToNet(&pom);
		package.buffor = reinterpret_cast<char*> (&pom);
		package.size=sizeof(pom);
		gameSock.SendTo(package, objects[0]);



	}
	void ConvertEventHostToNet(Event * event) {

		event->type = htonl(event->type);
		event->destination = htonl(event->destination);
		event->sender = htonl(event->sender);
	}

}Loop;

class NetObserver: public Component {
public:
	Socket gameSock;
	NetAddress server;
	NetUDPReceiver* receiver;
	Event event;
	fd_set master;
	timeval interval;

	NetObserver() {
		server.SetAddress("127.0.0.1", 50002);
		gameSock.CreateUDPRecevSocket(server);
		receiver = new NetUDPReceiver(gameSock);

		receiver->parent = &Loop;
		event.sender = 12;
		event.destination = 12;
		event.type = NET_RECV;
		FD_SET(gameSock.GetDescryptor(),&master);
		interval.tv_sec = 1;

	}
	void Start() {
		while (true) {
			if (select(gameSock.GetDescryptor() + 1, &master, NULL, NULL,
					&interval) == -1)
				throw SocketException("Select error");
			if (FD_ISSET(gameSock.GetDescryptor(),&master)) {
				cout << "Second: " << interval.tv_sec << " Nanosecond:"
						<< interval.tv_usec << endl;
				receiver->Updata(event);

			} else {
				cout <<".";
			}

			FD_ZERO(&master);
			FD_SET(gameSock.GetDescryptor(),&master);
			interval.tv_sec = 1;
		}
	}
	virtual void Updata(Event event) {

	}
	virtual void Intialization() {

	}
	virtual void Dispose() {

		delete receiver;
		gameSock.Close();
	}
	virtual void SendEvent(Event event) {
		cout << "Receive package " << sizeof(event) << " bytes, destination="
				<< event.destination << " sender=" << event.sender << " type="
				<< event.type << endl;
	}
	~NetObserver() {

	}
};
int main(int argc, char **argv) {
	try {
		NetObserver mainParent;
		mainParent.Start();

	} catch (SocketException e) {
		cout << e.GetMessage();
	}
	return 0;
}
